package com.fishingwithme.infrastructure.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

public class TencentGeocoderClient {
    private final String apiKey;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final String API_URL = "https://apis.map.qq.com/ws/geocoder/v1";

    public TencentGeocoderClient(RestTemplate restTemplate, String apiKey) {
        this.apiKey = apiKey;
        this.restTemplate = restTemplate;
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    // 正向地理编码
    public GeocoderResponse forward(String address, String city) throws Exception {
        URI uri = UriComponentsBuilder.fromHttpUrl(API_URL)
                .queryParam("address", address)
                .queryParam("city", city)
                .queryParam("key", apiKey)
                .queryParam("output", "json")
                .build()
                .toUri();
        return execute(uri);
    }

    // 反向地理编码
    public GeocoderResponse reverse(double lat, double lng) throws Exception {
        URI uri = UriComponentsBuilder.fromHttpUrl(API_URL)
                .queryParam("location", lat + "," + lng)
                .queryParam("key", apiKey)
                .queryParam("output", "json")
                .build()
                .toUri();
        return execute(uri);
    }

    private GeocoderResponse execute(URI uri) throws Exception {
        String json = restTemplate.getForObject(uri, String.class);
        return objectMapper.readValue(json, GeocoderResponse.class);
    }
}